<template>
    <view class="content">
        <!-- 加载提示框，初始隐藏，在数据加载时显示 -->
        <view class="custom-loading" v-if="isLoading || !mapFlag">
            <view class="loading-circle"></view>
            <view class="loading-text">{{loadingText}}</view>
        </view>
       
        <!-- 地图展示部分，根据定位或选择显示相应地图 -->
        <view class="content-map" v-show="mapFlag">
            <map style="width: 100%;height: 100%;" :latitude="latitude" :longitude="longitude"
                :markers="markers" @tap="tap" :scale="16" :title="title" enable-3D="true" show-compass="true"
                show-location="true" />
        </view>
        
        <!-- 地点列表展示部分，显示搜索到的相关地点信息 -->
        <view class="list" v-if="dataTips.length > 0 && mapFlag">
            <view class="item" v-for="(add,index) in dataTips" :key="add.id" @click="select(add,index)"
                :class="selectIndex==index?'active':''">
                <view class="name">{{add.name}}</view>
                <view class="address">{{add.district || ''}}{{add.address || ''}}</view>
            </view>
        </view>
    </view>
</template>

<script>
// 引入高德地图api提供的微信小程序的接口
import amapFile from '@/api/amap-wx.js';
// 创建地图
var myAmapFun = new amapFile.AMapWX({
    key: 'ef1e3285d4f509ebe7353c42e6cb7837'
}); //key值要申请为 去高德地图申请微信小程序的key

export default {
    data() {
        return {
            // 新增，控制加载提示框显示隐藏
            isLoading: false,
            loadingText: '正在加载，请稍候...',
            mapFlag: false,
            selectIndex: undefined,
            selectAddr: {},
            searchWords: "",
            id: 1, // 使用 marker点击事件 需要填写id
            title: 'map',
            latitude: 39.91667, // 纬度
            longitude: 116.41667, // 经度
            markers: [{
                latitude: 39.91667, // 纬度
                longitude: 116.41667, // 经度
                width: 40,
                height: 40,
                // iconPath: '',
                // iconPath: '/static/start.png'
            }],
            dataTips: []
        };
    },
    onLoad() {
        var self = this;
        // 显示加载提示框
        this.isLoading = true;
        uni.getLocation({
            type: 'gcj02',
            success: function (res) {
                if (res.errMsg == "getLocation:ok") {
                    self.longitude = res.longitude;
                    self.latitude = res.latitude;
                    self.$set(self.markers[0], "longitude", res.longitude);
                    self.$set(self.markers[0], "latitude", res.latitude);
                    self.mapFlag = true;
                    // 获取周边景点信息
                    self.getAroundPoi();
                }
            },
            fail: function (err) {
                self.showError('获取当前位置失败，请检查权限设置或网络连接', err);
            },
            complete: () => {
                this.isLoading = false;
            }
        });
    },
    methods: {
        // 统一的错误处理函数
        showError(message, errorDetails) {
            console.log(errorDetails);
            uni.showToast({
                title: message,
                icon: 'none'
            });
        },
        // 提取获取周边景点信息的方法，方便复用和维护
        getAroundPoi() {
            var self = this;
            myAmapFun.getPoiAround({
                location: self.longitude + ',' + self.latitude,
                radius: 5000,
                querykeywords: '景点',
                success: (data) => {
                    if (data && data.poisData) {
						console.log(data)
                        this.dataTips = data.poisData;
                    } else {
                        this.dataTips = [];
                    }
                },
                fail: (info) => {
                    this.showError('获取周边景点失败，请稍后重试', info);
                }
            });
        },
        // 根据地址列表中选择某一个地点
        select(add, index) {
            if (!add) {
                return;
            }
            this.selectIndex = index;
            var location = add.location.split(",");
            this.selectAddr = {
                address:add.name,
                detailAddress: add.pname+add.adname+add.address,
                latitude: location[1],
                longitude: location[0]
            };
			console.log(this.selectAddr.address)
			console.log(this.selectAddr.detailAddress)
			console.log(this.selectAddr)
            this.markers[0].latitude = +location[1];
            this.markers[0].longitude = +location[0];
            uni.setStorageSync("address", this.selectAddr.address);
            // 发起 getRegeo 请求
            this.getRegeoData();
        },
        // 获取逆地理编码信息（提取为单独方法）
      // 获取逆地理编码信息（提取为单独方法）
      getRegeoData() {
          var self = this;
          myAmapFun.getRegeo({
              location: this.markers[0].longitude + ',' + this.markers[0].latitude,
              success: (data) => {
                  // console.log("传输数据 - 成功路径");
                  // console.log("selectAddr:", this.selectAddr);
                  // console.log("regeo数据:", data);
                  
                  // 保持selectAddr的四个属性完整传递
                  const locationData = {
                      address: this.selectAddr.address, // 保持原样
                      detailAddress: this.selectAddr.detailAddress, // 保持原样
                      latitude: this.selectAddr.latitude, // 保持原样
                      longitude: this.selectAddr.longitude, // 保持原样
                      // 额外添加逆地理编码获取的信息（如果需要）
                      regeoData: data[0]?.regeocodeData || null
                  };
                  
                  // console.log("准备传递的数据:", locationData);
                  
                  uni.navigateTo({
                      url: `/pages/map/mapItem/mapItem?data=${encodeURIComponent(JSON.stringify(locationData))}`
                  });
              },
              fail: (info) => {
                  console.log("传输数据 - 失败路径");
                  console.log("selectAddr:", this.selectAddr);
                  
                  // 失败时也保持selectAddr四个属性完整传递
                  const locationData = {
                      address: this.selectAddr.address,
                      detailAddress: this.selectAddr.detailAddress,
                      latitude: this.selectAddr.latitude,
                      longitude: this.selectAddr.longitude
                  };
                  
                  console.log("准备传递的数据:", locationData);
                  
                  uni.navigateTo({
                      url: `/pages/map/mapItem/mapItem?data=${encodeURIComponent(JSON.stringify(locationData))}`,
                      success: () => {
                          uni.showToast({
                              title: '获取详细位置信息失败，但已跳转',
                              icon: 'none'
                          });
                      }
                  });
              }
          });
      },
        // 在地图上点击进行选点
        tap(e) {
            var location = e.detail.longitude + ',' + e.detail.latitude;
            var self = this;
            myAmapFun.getRegeo({
                location: location,
                success: (data) => {
                    this.selectAddr = {
                        address: data[0].regeocodeData.formatted_address,
                        latitude: e.detail.latitude,
                        longitude: e.detail.longitude
                    };
                    this.markers[0].latitude = data[0].latitude;
                    this.markers[0].longitude = data[0].longitude;
                    this.getAroundPoi();
                },
                fail: (info) => {
                    this.showError('点击地图获取信息失败，请重试', info);
                }
            });
        },
        
        cancel() {
            this.searchWords = '';
            this.getAroundPoi();
        }
    }
};
</script>

<style lang="scss" scoped>
page {
    font-family: 'PingFang SC', 'Microsoft YaHei', 'STKaiti', sans-serif;
    background-color: #f2f2f2;
    font-size: 16px;
}

.content {
    display: flex;
    flex-direction: column;
    height: 100vh;

    .inputCon {
        flex: 0 1 108rpx;
        width: 100%;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: center;

       
    }

    .content-map {
        width: 100%;
        height: 50vh;
        border: 1px solid #ccc;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 10px;
    }

    .list {
        border-radius: 30rpx;
        background-color: #fff;
        height: calc(50vh - 10upx);
        overflow-y: auto;
        width: 100%;
        margin: 0upx auto 0;
        padding-bottom: 20upx;

        /* 滚动条样式优化 */
        &::-webkit-scrollbar {
            width: 6px;
        }

        &::-webkit-scrollbar-track {
            background-color: #f2f2f2;
        }

        &::-webkit-scrollbar-thumb {
            background-color: #ccc;
            border-radius: 3px;
        }

        .item {
            border-bottom: 1px solid #f3f3f3;
            padding: 15px 30rpx;
            display: flex;
            flex-direction: column;

            &:last-child {
                border: none;
            }

            .address {
                font-size: 14px;
                color: #666;
                margin: 5px 0;
            }

            .name {
                font-size: 16px;
                color: #333;
                margin-top: 5px;
                font-weight: normal;
            }

            &.active {
                background-color: #f8f8f8;
                border-radius: 10px;

                .name {
                    font-weight: bold;
                    color: #E13500;
                }

                .address {
                    color: #E13500;
                }
            }
        }
    }
}

@media screen and (max-width: 600px) {
    .content.inputCon.searchView {
        width: 90%;
    }

    .content.content-map {
        height: 40vh;
    }

    .content.list {
        height: calc(60vh - 10upx);
    }
}


.custom-loading {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    
    .loading-circle {
        width: 50px;
        height: 50px;
        border: 5px solid #f3f3f3;
        border-top: 5px solid #E13500;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 15px;
    }
    
    .loading-text {
        font-size: 16px;
        color: #333;
    }
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>  